package com.pomty.pombook;

import java.util.Collections;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.codecarpet.fbconnect.FBLoginButton;
import com.codecarpet.fbconnect.FBPermissionActivity;
import com.codecarpet.fbconnect.FBRequest;
import com.codecarpet.fbconnect.FBSession;
import com.codecarpet.fbconnect.FBLoginButton.FBLoginButtonStyle;
import com.codecarpet.fbconnect.FBRequest.FBRequestDelegate;
import com.codecarpet.fbconnect.FBSession.FBSessionDelegate;

public class Main extends Activity {
	private static final String API_KEY = ""; // "<YOUR API KEY>";

	// Enter either your API secret or a callback URL (as described in documentation):
    private static final String API_SECRET = ""; // "<YOUR SECRET KEY>";
    private static final String GET_SESSION_PROXY = null; // "<YOUR SESSION CALLBACK)>";
    public static final String PHOTOUPLOADPERMISSION= "photo_upload";
    
     // /////////////////////////////////////////////////////////////////////////////////////////////////
    
    private FBSession mSession;
    private FBLoginButton mLoginButton;
    private Handler mHandler;
    private long sessionId;
    private String sessionName;
    private TextView mFacebookLabel;
    public static final int PERMISSIONREQUESTCODE = 1;
    
    private Button mLocalButton;
    private Button mAlbumFBButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    
		mHandler = new Handler();
		sessionId = 0;
		
		if (GET_SESSION_PROXY != null) {
            mSession = FBSession.getSessionForApplication_getSessionProxy(API_KEY, GET_SESSION_PROXY, new FBSessionDelegateImpl());
        } else {
            mSession = FBSession.getSessionForApplication_secret(API_KEY, API_SECRET, new FBSessionDelegateImpl());
        }
		
		setContentView(R.layout.main);
		
		mFacebookLabel = (TextView) findViewById(R.id.facebookLabel);
        mLoginButton = (FBLoginButton) findViewById(R.id.login);
        mLoginButton.setStyle(FBLoginButtonStyle.FBLoginButtonStyleWide);
		mLoginButton.setSession(mSession);
		
     
        mLocalButton = (Button)findViewById(R.id.local_button);
		mLocalButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        Uri uri = Images.Media.INTERNAL_CONTENT_URI;
		        uri = uri.buildUpon()
		                    .appendQueryParameter("bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
		        
		        Intent intent = new Intent(v.getContext(), ImageGallery.class);
		        intent.setData(uri);
		        intent.putExtra("windowTitle", getString(R.string.localAlbumName));
		        intent.putExtra("mediaTypes", ImageManager.INCLUDE_IMAGES);
		        v.getContext().startActivity(intent);
			 	
			}
		});
		mAlbumFBButton = (Button) findViewById(R.id.albums_fb_button);
		mAlbumFBButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//Intent intent = new Intent(v.getContext(), AlbumsFBActivity.class);
				Intent intent = new Intent(v.getContext(), FBGalleryPicker.class);
			 	v.getContext().startActivity(intent);
			}
		});
		

		
//		int fbwidth = mAlbumFBButton.getLayoutParams().width;
//		int camwidth = mLocalButton.getLayoutParams().width;
//		if (fbwidth >= camwidth)
//		{
//			LayoutParams params = new LayoutParams();
//			
//			params.width = fbwidth;
//			mLocalButton.setLayoutParams(params);
//			//mLocalButton.setWidth(fbwidth);
//		}
//		else
//			mAlbumFBButton.setWidth(camwidth);
		
		
		mSession.resume(this);
		
	}
	
	private void askPermission() {
        Intent intent = new Intent(this, FBPermissionActivity.class);
        intent.putExtra("permissions", new String[]{PHOTOUPLOADPERMISSION});
        intent.putExtra("countryCode", getResources().getConfiguration().locale.getLanguage());
        this.startActivityForResult(intent, PERMISSIONREQUESTCODE );
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	if (mSession.isConnected())
		{
    		MenuItem item = menu.add(Menu.NONE, Menu.NONE, Menu.NONE, R.string.permissionPhotoUpload);
    		item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				
				@Override
				public boolean onMenuItemClick(MenuItem item) {
					checkPermissionAndLaunchActivity();
					return true;
				}
			});
    		item.setIcon(R.drawable.ic_menu_multiselect_gallery);
		}
		return super.onCreateOptionsMenu(menu);
	}

	private void checkPermissionAndLaunchActivity() {
    	String fql = "select " + PHOTOUPLOADPERMISSION + " from permissions where uid == " + String.valueOf(mSession.getUid());
		Map<String, String> params = Collections.singletonMap("query", fql);
		FBRequest.requestWithDelegate(new FBHasPermissionLaunchActivity()).call("facebook.fql.query", params);
	}    
	

    
    public class FBHasPermissionLaunchActivity extends FBRequestDelegate {
		@Override
		public void requestDidFailWithError(FBRequest request,
				Throwable error) {
			// TODO Auto-generated method stub
			
			super.requestDidFailWithError(request, error);
		}

		@Override
		public void requestWasCancelled(FBRequest request) {
			// TODO Auto-generated method stub
			super.requestWasCancelled(request);
		}

		@Override
		public void requestDidLoad(FBRequest request, Object result) {
            int hasPermission = 0;
            
            if (result instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) result;
                try {
                    JSONObject jo = jsonArray.getJSONObject(0);
                    hasPermission = jo.getInt(PHOTOUPLOADPERMISSION);
                    if (hasPermission == 0)
                    {
                        mHandler.post(new Runnable() {
                            public void run() {
                                askPermission();
                            }
                         });
                    }
                    else
                    {
                    	mHandler.post(new Runnable() {
                            public void run() {
                            	Toast.makeText(getApplicationContext(), R.string.alreadyAllowedPermission, Toast.LENGTH_LONG).show();
                            }
                         });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
    private class FBSessionDelegateImpl extends FBSessionDelegate {
    	@Override
        public void sessionDidLogin(FBSession session, Long uid) {
            sessionId = session.getUid();
            
            Thread worker = new Thread(new Runnable() {
        		public void run() {
    				String fql = "select uid,name from user where uid == " + sessionId;
    				Map<String, String> params = Collections.singletonMap("query", fql);
    				
    				FBRequest.requestWithDelegate(new FBRequestDelegateImpl()).call("facebook.fql.query", params);
    			}
            });
            worker.start();
        }
    	
    	@Override
        public void sessionDidLogout(FBSession session) {
            mHandler.post(new Runnable() {
                public void run() {
                	mFacebookLabel.setText(getString(R.string.facebook));
                }});
        }
    }
	
	
    private class FBRequestDelegateImpl extends FBRequestDelegate {
    	
    	@Override
        public void requestDidLoad(FBRequest request, Object result) {
            
            String name = null;
            
            if (result instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) result;
                try {
                    JSONObject jo = jsonArray.getJSONObject(0);
                    name = jo.getString("name");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            sessionName = name;
            mHandler.post(new Runnable() {
                public void run() {
                	mFacebookLabel.setText(getString(R.string.loggedInAs) + " " + sessionName);
                }});
        }
    }
}